package com.itestor.iptv.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * @author Mr.li
 */
public class LocalCmdUtil {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(LocalCmdUtil.class);

    /**
     * get sc command line
     * @param localServiceName
     * @param command
     * @return String[]
     */
    public static String[] genSCCmdlines(String command, String localServiceName) {
        return new String[] { "cmd", "/c",
                "sc " + command + " \"" + localServiceName + "\"" };
    }

    /**
     * get ntp command line
     * @param netServer
     * @param command
     * @return String[]
     */
    public static String[] genNtpCmdlines(String command, String netServer) {
        return new String[] { "cmd", "/c",
                "net time " + command + "\"" + netServer + "\"" };
    }


    /**
     * get ntp command line
     * @param command
     * @return String[]
     */
    public static String[] genNtpQueryCmd(String command) {
        return new String[] { "cmd", "/c",
                "net time " + command };
    }

    
    /**
     * get time command line
     * @param time
     * @return String[]
     */
    public static String[] getTimeCmdLines(String time) {
        return new String[] { "cmd", "/c", "time " + time };
    }

    /**
     * Get date command line
     * @param date
     * @return String[]
     */
    public static String[] getDateCmdLines(String date) {
        return new String[] { "cmd", "/c", "date " + date };
    }

    /**
     * get netsh command line
     * @param macAlias
     * @param address
     * @param netmask
     * @param gateway
     * @return String[]
     */
    public static String[] getAddrCmdLines(String macAlias, String address,
            String netmask, String gateway) {
        return new String[] {
                "cmd",
                "/c",
                "netsh interface ip set addr " + macAlias + " static "
                        + address + " " + netmask + " " + gateway };
    }

    /**
     * 修改系统时间命令
     * @param timeCmdMsg
     */
    public static void execTimeCmd(String[] timeCmdMsg) {
        String date = timeCmdMsg[0];
        String time = timeCmdMsg[1];

        String[] timeMsg = getTimeCmdLines(time);
        ProcessBuilder timeBuilder = new ProcessBuilder(timeMsg);
        timeBuilder.redirectErrorStream(true);

        String[] dateMsg = getDateCmdLines(date);
        ProcessBuilder dateBuilder = new ProcessBuilder(dateMsg);
        dateBuilder.redirectErrorStream(true);

        try {
            dateBuilder.start();
        } catch (IOException ex) {
            String errMgs = ex.toString();
            logger.error("runCmd errMsg [" + errMgs + "]");
        }

        try {
            timeBuilder.start();
        } catch (IOException ex) {
            String errMgs = ex.toString();
            logger.error("runCmd errMsg [" + errMgs + "]");
        }
    }

    /**
     * 执行修改IP的命令.
     * @param macAlias
     * @param address
     * @param netmask
     * @param gateway
     */
    public static void execNetshCmd(String macAlias, String address,
            String netmask, String gateway) {
        String[] netshCmdMsg = getAddrCmdLines(macAlias, address, netmask,
                gateway);
        ProcessBuilder builder = new ProcessBuilder(netshCmdMsg);
        builder.redirectErrorStream(true);

        try {
            builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行启动服务脚本
     * @param command
     * @param localServiceName
     * @return Integer
     */
    public static Integer execScCmd(String command, String localServiceName) {
        String[] scCmdMsg = genSCCmdlines(command, localServiceName);

        ProcessBuilder builder = new ProcessBuilder(scCmdMsg);
        builder.redirectErrorStream(true);
        Process process = null;
        InputStream in = null;

        try {
            process = builder.start();
            in = process.getInputStream();
        } catch (IOException ex) {
            String errMgs = ex.toString();
            logger.error("runCmd errMsg [" + errMgs + "]");
        }

        List<String> readLineList = new ArrayList<String>();
        String readLine = null;

        try {
            LineNumberReader reader = new LineNumberReader(
                    new InputStreamReader(in, "UTF-8"), 100);
            while ((readLine = reader.readLine()) != null) {
                if (readLine.trim().equals("")) {
                    continue;
                }
                readLineList.add(readLine);
                logger.debug(readLine);
            }
        } catch (IOException ex) {
            logger.error("runCmd errMsg [" + ex.getMessage() + "]");
        }

        int state = LocalCmdDataParser.parseScCmdDataLines(readLineList);
        return state;

    }

    /**
     * 修改 ntp.server.
     * @param command
     * @param ntpServer
     */
    public static void execNtpCmd(String command, String ntpServer) {
        String[] scCmdMsg = genNtpCmdlines(command, ntpServer);

        ProcessBuilder builder = new ProcessBuilder(scCmdMsg);
        builder.redirectErrorStream(true);
        Process process = null;
        try {
            process = builder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 修改 ntp.server.
     * @param command
     * @param ntpServer
     * @return String.
     */
    public static String execGetNtpServerCmd(String command) {
        String[] scCmdMsg = genNtpQueryCmd(command);

        ProcessBuilder builder = new ProcessBuilder(scCmdMsg);
        builder.redirectErrorStream(true);
        Process process = null;
        InputStream in = null;
        try {
            process = builder.start();
            in = process.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }

        String readLine = null;
        try {
            LineNumberReader reader = new LineNumberReader(
                    new InputStreamReader(in, "UTF-8"), 100);
            while ((readLine = reader.readLine()) != null) {
                if (readLine.trim().equals("")) {
                    continue;
                }
                if (readLine.contains("当前 SNTP 值为")){
                    readLine.substring(readLine.indexOf(":")+1);
                    logger.info("["+readLine+"]");
                    break;
                }
                logger.info(readLine);                
            }
        } catch (IOException ex) {
            logger.error("runCmd errMsg [" + ex.getMessage() + "]");
        }        
        return readLine;
    }

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        // logger.info(genSCCmdlines("stop", "mysql"));
        // runCmd(genSCCmdlines("stop", "mysql"));

        // execNetshCmd("本地连接 2", "192.168.8.99", "255.255.255.0",
        // "192.168.8.254");

        // execTimeCmd(new String[] {"2010-10-13","22:34:45"});

        execNtpCmd("/setsntp:", "time-nw.nist.gov");

    }

}
